package wealk.android.jewels;

import java.util.HashMap;

import org.anddev.andengine.util.MathUtils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.xkdx.caipiao.R;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.UserActivity;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.my.setup.PointModule.Point;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.presistence.checklogin.CheckLoginTokenAction;
import com.xkdx.guangguang.presistence.checklogin.CheckLoginTokenModule;
import com.xkdx.guangguang.presistence.checklogin.CheckLoginTokenPresistence;
import com.xkdx.guangguang.util.AESUtil;
import com.xkdx.guangguang.util.SharePrefenceUtil;

public class GameHomeFragment extends BaseFragment {
	View view;
	BaseFragment baseFragment;
	String[] markIconPath = new String[9];
	int[] markBonus = new int[9];
	LinearLayout game_dialog, gameHelp;
	ImageView gameexchange, brandRemove, gameRank, game_start, game_frmcancle;
	Drawable game_home1, game_home2, game_home3, game_home4, game_home5;
	ProgressDialog pd;
	Point point;
	BaseFragment gameFragment;
	UploadPointAction uploadPointAction;
	UploadPointModule uploadPointModule;
	UploadPointPresistence uploadPointPresistence;
	boolean isLoginOutDate, isLogin;
	// 检测登录过期
	CheckLoginTokenAction checkLoginTokenAction;
	CheckLoginTokenModule checkLoginTokenModule;
	CheckLoginTokenPresistence checkLoginTokenPresistence;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.game_home, container, false);
		findView();
		setOnClick();
		checkLogin();
		return view;
	}

	private void checkLogin() {
		SharePrefenceUtil su = new SharePrefenceUtil(getActivity(), IConstants.SP_USER);
		if (!su.getUserLoginToken().equals("")) {
			isLogin = true;
			dataLoadDialog.setMessage("正在检查登录状态...");
			dataLoadDialog.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					getActivity().finish();
				}
			});
			dataLoadDialog.show();

			checkLoginTokenAction = new CheckLoginTokenAction(su.getUserID(), su.getUserLoginToken());
			checkLoginTokenModule = new CheckLoginTokenModule();
			checkLoginTokenPresistence = new CheckLoginTokenPresistence(this);
			((ManagerActivity) getActivity()).addCurrentTask(checkLoginTokenPresistence);
			checkLoginTokenPresistence.setActitons(checkLoginTokenAction);
			checkLoginTokenPresistence.setModule(checkLoginTokenModule);
			checkLoginTokenPresistence.execute();
		} else {
			isLogin = false;
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		if (View.VISIBLE != game_dialog.getVisibility()) {
			game_start.setClickable(true);
			gameexchange.setClickable(true);
		}
		if (isLogin && isLoginOutDate && (Jewels.SUBMITSCORE == 1 || Jewels.SUBMITANDINTENT == 1)) {
			showLoading();
		}

		super.onResume();
	}

	@Override
	public void findView() {
		pd = new ProgressDialog(getActivity());
		pd.setMessage("正在提交...");
		baseFragment = this;
		gameexchange = (ImageView) view.findViewById(R.id.game_exchange);
		brandRemove = (ImageView) view.findViewById(R.id.game_brand_remove);
		gameRank = (ImageView) view.findViewById(R.id.game_ranking);
		gameHelp = (LinearLayout) view.findViewById(R.id.game_help);
		game_start = (ImageView) view.findViewById(R.id.game_start);
		game_dialog = (LinearLayout) view.findViewById(R.id.game_dialog);
		game_frmcancle = (ImageView) view.findViewById(R.id.game_frmcancle);
	}

	@Override
	public void showLoading() {
		SharePrefenceUtil su = new SharePrefenceUtil(getActivity(), IConstants.SP_USER);
		String score = "";
		if (Jewels.intentScore != 0) {
			score = String.valueOf(Jewels.intentScore);
		}
		StringBuffer sb = new StringBuffer(score);
		while (16 - sb.length() != 0) {
			sb.append("\n");
		}
		score = AESUtil.aesEncrypt(sb.toString());
		uploadPointAction = new UploadPointAction(su.getUserID(), su.getUserLoginToken(), score);
		uploadPointModule = new UploadPointModule();
		uploadPointPresistence = new UploadPointPresistence(this);
		((ManagerActivity) getActivity()).addCurrentTask(uploadPointPresistence);
		uploadPointPresistence.setActitons(uploadPointAction);
		uploadPointPresistence.setModule(uploadPointModule);
		uploadPointPresistence.execute();
		pd.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (uploadPointPresistence != null) {
					uploadPointPresistence.cancel(true);
				}
				getActivity().finish();

			}
		});
		pd.show();

	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
		pd.dismiss();
		if (map.containsKey("0")) {
			if (uploadPointModule.isUpLoadPointSuccess) {
				Toast.makeText(getActivity(), "提交成功", Toast.LENGTH_SHORT).show();
				SharePrefenceUtil su = new SharePrefenceUtil(getActivity(), IConstants.SP_USER);
				int point = Jewels.intentScore + Integer.valueOf(su.getUserPoint());
				su.setUserPoint(String.valueOf(point));
				Jewels.SUBMITSCORE = 0;
				Jewels.intentScore = 0;
				if (Jewels.SUBMITANDINTENT == 1) {
					Intent intent = new Intent(getActivity(), UserActivity.class);
					startActivity(intent);
				}
			} else {
				reSubmit();
			}
		} else {
			reSubmit();
		}

	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
		dataLoadDialog.dismiss();
		if (map.containsKey("0")) {
			if (checkLoginTokenModule.isLoginOutDate) {
				isLoginOutDate = true;
			} else {
				isLoginOutDate = false;
				Toast.makeText(getActivity(), "登录已过期，请重新登录", Toast.LENGTH_SHORT).show();
			}

		} else {
			refresh(map);
		}

	}

	@Override
	public void setOnClick() {

		game_frmcancle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				game_start.setClickable(true);
				gameexchange.setClickable(true);
				game_dialog.setVisibility(View.GONE);
			}
		});
		gameRank.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				game_dialog.setVisibility(View.VISIBLE);
				game_start.setClickable(false);
				gameexchange.setClickable(false);
			}
		});

		gameexchange.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				IConstants.BottomBtnSelected = 5;
				Intent intent = new Intent(getActivity(), UserActivity.class);
				intent.putExtra("fragment", "ExchangeShopFragment");
				startActivity(intent);
			}
		});
		game_dialog.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				game_dialog.setVisibility(View.GONE);
				game_start.setClickable(true);
				gameexchange.setClickable(true);
			}
		});

		game_start.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				game_start.setClickable(false);
				final Intent intent = new Intent(getActivity(), Jewels.class);

				String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()
						+ "/GuangGuang/user/head.jpg";
				intent.putExtra("userPicFile", filePath);
				String[] markIconPath = new String[2];
				int style1 = MathUtils.random(1, 8);
				int style2 = MathUtils.random(1, 8);
				markIconPath[0] = "h" + Integer.valueOf(style1) + ".png";
				markIconPath[1] = "l" + Integer.valueOf(style2) + ".png";
				intent.putExtra("markIconPath", markIconPath);

				SharePrefenceUtil su = new SharePrefenceUtil(getActivity(), IConstants.SP_USER);
				String nickName = su.getUserNickName();
				String userPoint = su.getUserPoint();
				if (nickName == "" && userPoint == "") {

					Dialog dialog = new AlertDialog.Builder(getActivity()).setMessage("您未登陆，游戏后不能提交积分")
							.setCancelable(false).setPositiveButton("继续游戏", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									startActivity(intent);
								}
							}).setNeutralButton("用户登录", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									IConstants.BottomBtnSelected = 5;
									Intent intent = new Intent(getActivity(), UserActivity.class);
									intent.putExtra("fragment", "UserLoginFragment");
									startActivity(intent);
								}
							}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									game_start.setClickable(true);
									gameexchange.setClickable(true);
								}
							}).create();
					dialog.show();
				} else {
					intent.putExtra("userName", su.getUserNickName());
					intent.putExtra("totalscore", Integer.valueOf(su.getUserPoint()));
					Jewels.isLogin = true;
					startActivity(intent);
				}
			}
		});

		if (View.VISIBLE == game_dialog.getVisibility()) {
			game_start.setClickable(false);
			gameexchange.setClickable(false);
		} else {
			game_start.setClickable(true);
			gameexchange.setClickable(true);
		}

	}

	@Override
	public void onDestroy() {
		Jewels.SUBMITANDINTENT = 0;
		Jewels.SUBMITSCORE = 0;
		Jewels.intentScore = 0;
		super.onDestroy();
	}

}
